<?php

namespace common\models\c2\entity;

use common\components\oss\OSS;
use Yii;

/**
 * This is the model class for table "{{%fe_user}}".
 *
 * @property integer $id
 * @property integer $muid
 * @property integer $proprietor_id
 * @property integer $community_id
 * @property integer $building_number_id
 * @property integer $unit_id
 * @property integer $house_id
 * @property string $password_hash
 * @property integer $type
 * @property string $username
 * @property string $mobile_number
 * @property string $id_number
 * @property string $email
 * @property string $balance
 * @property string $address
 * @property integer $status
 * @property string $created_at
 * @property string $updated_at
 */
class FeUser extends \cza\base\models\ActiveRecord
{
    public $idcard_front;
    public $idcard_back;
    public $estate;
    const STATUS_UN_AUDIT = 10;

    public function fields()
    {
        return [
            'id',
            'muid',
            'proprietor_id',
            'community_id',
            'building_number_id',
            'unit_id',
            'house_id',
            'username',
            'address',
            'mobile_number',
            'status',
            'community_name' => function ($model) {
                return $model->community->name;
            },
            'validity_day' => function ($model) {
                $vip = $model->vip;
                if ($vip) {
                    return $model->vip->active_day;
                }
                return 0;
            },
        ];
    }

    /**
     * @inheritdoc
     */
    public static function tableName()
    {
        return '{{%fe_user}}';
    }

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['muid', 'proprietor_id', 'community_id', 'building_number_id', 'unit_id', 'house_id', 'type'], 'integer'],
            [['balance'], 'number'],
            [['created_at', 'updated_at'], 'safe'],
            [['password_hash'], 'string', 'max' => 64],
            [['username', 'email', 'address'], 'string', 'max' => 255],
            [['mobile_number', 'id_number'], 'string', 'max' => 20],
            [['status'], 'integer', 'max' => 127],
        ];
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return [
            'id' => Yii::t('app.c2', 'ID'),
            'muid' => Yii::t('app.c2', 'Muid'),
            'proprietor_id' => Yii::t('app.c2', 'Proprietor ID'),
            'community_id' => Yii::t('app.c2', 'Community ID'),
            'building_number_id' => Yii::t('app.c2', 'Building Number ID'),
            'unit_id' => Yii::t('app.c2', 'Unit ID'),
            'house_id' => Yii::t('app.c2', 'House ID'),
            'password_hash' => Yii::t('app.c2', 'Password Hash'),
            'type' => Yii::t('app.c2', 'Type'),
            'username' => Yii::t('app.c2', 'Username'),
            'mobile_number' => Yii::t('app.c2', 'Mobile Number'),
            'id_number' => Yii::t('app.c2', 'Id Number'),
            'email' => Yii::t('app.c2', 'Email'),
            'balance' => Yii::t('app.c2', 'Balance'),
            'address' => Yii::t('app.c2', 'Address'),
            'status' => Yii::t('app.c2', 'Status'),
            'created_at' => Yii::t('app.c2', 'Created At'),
            'updated_at' => Yii::t('app.c2', 'Updated At'),
        ];
    }

    /**
     * @inheritdoc
     * @return \common\models\c2\query\FeUserQuery the active query used by this AR class.
     */
    public static function find()
    {
        return new \common\models\c2\query\FeUserQuery(get_called_class());
    }
    
    /**
    * setup default values
    **/
    public function loadDefaultValues($skipIfSet = true) {
        parent::loadDefaultValues($skipIfSet);
    }

    public function afterSave($insert, $changedAttributes)
    {
        parent::afterSave($insert, $changedAttributes); // TODO: Change the autogenerated stub
        if ($insert) {
            if (!empty($this->idcard_front)) {
                $attachment = new EntityAttachment();
                $attachment->entity_id = $this->id;
                $attachment->entity_class = self::className();
                $attachment->entity_attribute = 'idcard_front';
                $attachment->url = $this->idcard_front;
                $attachment->save();
            }
            if (!empty($this->idcard_back)) {
                $attachment = new EntityAttachment();
                $attachment->entity_id = $this->id;
                $attachment->entity_class = self::className();
                $attachment->entity_attribute = 'idcard_back';
                $attachment->url = $this->idcard_back;
                $attachment->save();
            }
            if (!empty($this->estate)) {
                $attachment = new EntityAttachment();
                $attachment->entity_id = $this->id;
                $attachment->entity_class = self::className();
                $attachment->entity_attribute = 'estate';
                $attachment->url = $this->estate;
                $attachment->save();
            }
        }
    }

    /**
     * Validates password
     *
     * @param string $password password to validate
     * @return bool if password provided is valid for current user
     */
    public function validatePassword($password)
    {
        return Yii::$app->security->validatePassword($password, $this->password_hash);
    }

    /**
     * Generates password hash from password and sets it to the model
     *
     * @param string $password
     */
    public function setPassword($password)
    {
        $this->password_hash = Yii::$app->security->generatePasswordHash($password);
    }

    /**
     * Generates "remember me" authentication key
     */
    public function generateAuthKey()
    {
        $this->auth_key = Yii::$app->security->generateRandomString();
    }

    public function getIdcardFront()
    {
        // return $this->getAttachment()->where(['entity_class' => self::className(), 'entity_attribute' => 'idcard_front'])
        //     ->one();
        return $this->hasOne(EntityAttachment::className(), ['entity_id' => 'id']);
    }

    public function getIdcardBack()
    {
        return $this->hasOne(EntityAttachment::className(), ['entity_id' => 'id']);
    }

    public function getEstate()
    {
        return $this->hasOne(EntityAttachment::className(), ['entity_id' => 'id']);
    }

    public function getAttachment($entity_attribute = null)
    {
        return EntityAttachment::find()->where([
            'entity_id' => $this->id,
            'entity_class' => self::className(),
            'entity_attribute' => $entity_attribute,
        ])->one();
    }

    public function getAttachmentUrl($entity_attribute = null)
    {
        $model = EntityAttachment::find()->where([
            'entity_id' => $this->id,
            'entity_class' => self::className(),
            'entity_attribute' => $entity_attribute,
        ])->one();
        if ($model) {
            return OSS_URL . '/' . $model->url;
        }
        return '';
    }

    public function getCommunity()
    {
        return $this->hasOne(Community::className(), ['id2' => 'community_id']);
    }

    public function getVip()
    {
        return $this->hasOne(UserVip::className(), ['user_id' => 'id']);
    }

}
